package yiran.stock.command;

import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import yiran.stock.Stock;
import yiran.stock.StockCommand;
import yiran.stock.StockManager;
import yiran.stock.data.DatabaseManager;
import yiran.stock.lang.LangHelper;
import yiran.stock.output.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BuyCommand implements StockSubCommand {
    @Override
    public boolean execute(CommandSender sender, String[] args, Stock plugin, StockManager stockManager) {
        if (!stockManager.isMarketOpen()) {
            sender.sendMessage(LangHelper.getString("errors.market-closed"));
            return true;
        }

        Economy economy = plugin.getEconomy();
        if (economy == null || plugin.isEconomyEnabled()) {
            sender.sendMessage(LangHelper.getString("errors.economy-not-ready"));
            return true;
        }

        if (!(sender instanceof Player)) {
            sender.sendMessage(LangHelper.getString("errors.only-player-buy"));
            return true;
        }

        if (args.length < 2) {
            sender.sendMessage(LangHelper.getString("commands.buy-usage"));
            return true;
        }

        Player player = (Player) sender;
        String symbol = args[0].toUpperCase();
        int quantity;

        if (!stockManager.addStockToConfig(symbol)) {
            sender.sendMessage(LangHelper.getString("errors.stock-not-found", symbol));
            return true;
        }

        try {
            quantity = Integer.parseInt(args[1]);
            if (quantity <= 0) throw new NumberFormatException();
        } catch (NumberFormatException e) {
            sender.sendMessage(LangHelper.getString("commands.invalid-quantity"));
            return true;
        }

        if (args.length > 2 && "confirm".equalsIgnoreCase(args[2])) {
            return processBuyTransaction(sender, stockManager, player, symbol, quantity, economy);
        } else {
            if (!stockManager.loadStockIfNeeded(symbol)) {
                sender.sendMessage(LangHelper.getString("errors.stock-not-found", symbol));
                return true;
            }

            Double price = stockManager.getStockPrice(symbol);
            if (price == null) {
                sender.sendMessage(LangHelper.getString("errors.stock-not-found", symbol));
                return true;
            }

            double totalCost = price * quantity;
            player.sendMessage(LangHelper.getSafeString("stocks.buy-confirm",
                    quantity,
                    stockManager.getStockName(symbol),
                    totalCost));
            player.sendMessage(LangHelper.getSafeString("commands.confirm-instruction",
                    symbol,
                    quantity));
            return true;
        }
    }

    public static boolean processBuyTransaction(CommandSender sender, StockManager stockManager,
                                                Player player, String symbol, int quantity, Economy economy) {
        Double price = stockManager.getStockPrice(symbol);
        if (price == null) {
            sender.sendMessage(LangHelper.getString("errors.stock-not-found", symbol));
            return false;
        }

        double totalCost = price * quantity;
        if (!economy.has(player, totalCost)) {
            sender.sendMessage(LangHelper.getString("errors.insufficient-funds", totalCost));
            return false;
        }

        EconomyResponse response = economy.withdrawPlayer(player, totalCost);
        if (!response.transactionSuccess()) {
            sender.sendMessage(LangHelper.getString("errors.transaction-failed", response.errorMessage));
            return false;
        }

        try {
            DatabaseManager.addHolding(player.getName(), symbol, quantity, price);
        } catch (Exception e) {
            economy.depositPlayer(player, totalCost);
            sender.sendMessage(LangHelper.getString("errors.transaction-failed", "数据库操作失败"));
            Logger.error("添加持仓失败: " + e.getMessage());
            return false;
        }

        player.sendMessage(LangHelper.getString("stocks.buy-success", quantity, stockManager.getStockName(symbol), totalCost));
        Logger.info(player.getName() + " bought " + quantity + " shares of " + symbol + " for " + totalCost);
        return true;
    }

    @Override
    public List<String> tabComplete(CommandSender sender, String[] args, StockManager stockManager) {
        return StockCommand.getStockSymbolCompletions(args, stockManager);
    }
}
